package com.legal.framework.security.filter;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import com.legal.common.core.domain.model.LoginUser;
import com.legal.common.utils.SecurityUtils;
import com.legal.common.utils.StringUtils;
import com.legal.framework.web.service.TokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; // 添加日志依赖

/**
 * token过滤器 验证token有效性
 *
 * @author ruoyi
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
{
    private static final Logger log = LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class);
    // 初始化日志实例

    @Autowired
    private TokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        log.info("JwtAuthenticationTokenFilter: 获取到的loginUser: {}", loginUser);
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication()))
        {
            log.info("JwtAuthenticationTokenFilter: 验证token并设置认证信息");
            tokenService.verifyToken(loginUser);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            log.info("JwtAuthenticationTokenFilter: 认证信息设置成功: {}", authenticationToken);
        }
        else if (StringUtils.isNull(loginUser))
        {
            log.info("JwtAuthenticationTokenFilter: 未获取到loginUser，请求路径: {}", request.getRequestURI());
        }
        else
        {
            log.info("JwtAuthenticationTokenFilter: 已存在认证信息，无需重复设置");
        }
        chain.doFilter(request, response);
    }
}
